/**
 * 共享的数据库连接配置
 * 为所有模型提供统一的Sequelize实例
 */

const { Sequelize } = require('sequelize');
const dbConfig = require('./db');
const { logInfo, logError } = require('../logger');

// 创建单一的Sequelize实例
const sequelize = new Sequelize(
  dbConfig.database,
  dbConfig.username,
  dbConfig.password,
  {
    host: dbConfig.host,
    port: dbConfig.port,
    dialect: dbConfig.dialect,
    logging: dbConfig.logging,
    pool: dbConfig.pool,
    sync: { force: false, alter: false } // 禁用alter选项避免自动修改表结构
  }
);

/**
 * 测试数据库连接的函数
 * 避免在模块加载时直接连接数据库
 */
async function testConnection() {
  try {
    await sequelize.authenticate();
    logInfo('数据库连接成功');
    return true;
  } catch (error) {
    logError('数据库连接失败', { error: error.message });
    return false;
  }
}

module.exports = {
  sequelize,
  testConnection
};